<template>
    <div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" status-icon>

            <div style="margin-bottom: 5%">
                <el-form-item prop="regTelphone">
                    <el-input
                            placeholder="请输入手机号"
                            maxlength="11"
                            v-model.number="ruleForm.regTelphone">
                        <i slot="prefix" class="phonePic"></i>
                    </el-input>
                </el-form-item>
            </div>
            <div style="margin-bottom: 5%">
                <el-form-item prop="regUsername">
                    <el-input
                            placeholder="中、英文均可，最长18个字符"
                            v-model="ruleForm.regUsername"
                            maxlength="14"
                            autocomplete="off">
                        <i slot="prefix" class="namePic"></i>
                    </el-input>
                </el-form-item>
            </div>
            <div style="margin-bottom: 5%">
                <el-form-item prop="regPassword">
                    <el-input
                            placeholder="密码为5-20位英文、数字、符号，区分大小写"
                            maxlength="20"
                            type="password"
                            v-model="ruleForm.regPassword"
                            autocomplete="off">
                        <i slot="prefix" class="passPic"></i>
                    </el-input>
                </el-form-item>
            </div>
            <div style="margin-bottom: 5%;display: flex;justify-content: space-between;">
                <el-form-item prop="codeNumber" style="margin-bottom: 0px;display: inline-block;  float: left;">
                    <el-input
                        placeholder="请填写短信验证码"
                        v-model="ruleForm.codeNumber"
                        autocomplete="off"
                        @keyup.enter.native="submitForm('ruleForm')">
                    </el-input>
                </el-form-item>

                <el-button style="display: inline-block; " type="info" plain @click="getPhoneCode" :disabled="btnDisabled">{{button}}</el-button>
            </div>
            <div>
                <el-form-item>
                    <el-button class="regButton" @click="submitForm('ruleForm')" v-if="showSome==1">注册</el-button>
                    <el-button class="regButton bingBtn" v-if="showSome==4">绑定</el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
    export default {
        name: "register",
        data() {
            //手机号验证
            var checkPhone = (rule, value, callback) => {
                this.ruleForm.regTelphone = value
                console.log(numLength)
                var numLength = value.toString().length
                if (!value) {
                    return callback(new Error('请检查或重新输入手机号'));
                }
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        if (numLength < 11) {
                            callback(new Error('请检查填写正确的手机号码'));
                        } else {
                            callback();
                        }
                    }
                }, 500);
            };
            //用户名验证
            var validateName = (rule, value, callback) => {
                var nameLength = value.toString().length
                this.ruleForm.regUsername = value
                if (value === '') {
                    return callback(new Error('请输入用户名'));
                }
                setTimeout(() => {
                    if (value !== '') {
                        if (!this.checks(value)) {
                            if (nameLength < 2) {
                                callback(new Error('请输入超过1个字符'));
                            } else {
                                callback();
                            }
                        } else {
                            callback(new Error('您输入了非法字符，请重新输入'));
                        }
                    }
                }, 500);
            };
            //密码验证
            var validatePass = (rule, value, callback) => {
                this.ruleForm.regPassword = value
                var passLength = value.length
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (value !== '') {
                        if (passLength < 5) {
                            callback(new Error('请输五个以上的字符'));
                        }
                    }
                    callback();
                }
            };
            //验证码
            var validateCode = (rule, value, callback) => {
                this.ruleForm.codeNumber = value
                // console.log(this.ruleForm.codeNumber)
                if (value === '') {
                    callback(new Error('请输入验证码'));
                } else {
                    if (value !== '') {
                        callback();
                    }
                    callback();
                }
            };

            return {
                showFind: '',
                button: '获取验证码',
                btnDisabled: false,
                totalTime: 60,     //记录具体倒计时时间
                //注册表单验证
                ruleForm: {
                    regTelphone: '',
                    regPassword: '',
                    regUsername: '',
                    codeNumber: '',
                },

                rules: {
                    regTelphone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                    regPassword: [
                        {validator: validatePass, trigger: 'blur'}
                    ],
                    regUsername: [
                        {validator: validateName, trigger: 'blur'}
                    ],
                    codeNumber: [
                        {validator: validateCode, trigger: 'blur'}
                    ],
                },
            }
        },
        props: ["showSome", "showHook"],
        methods: {
            changeShow(e) {
                this.showFind = e;
                // console.log(e)
                this.$emit('findShow', this.showFind)
            },
            //检测非法字符
            /**验证输入框是否非法字符  是非法字符 则返回true**/
            checks(newName) {
                var regEn = /[`!@#$%^&*()_+<>?:"{},.\/;'[\]]/im,
                    regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;
                if (regEn.test(newName) || regCn.test(newName)) {
                    return true;
                }
                return false;
            },
            //验证表单
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.subRegister()
                    } else {
                        console.log('注册失败!');
                        return false;
                    }
                });
            },

            // 倒计时
            countdown() {
                this.button = this.totalTime + 's后重新发送'
                this.btnDisabled = 'disabled'
                let clock = window.setInterval(() => {
                    this.totalTime--
                    this.button = this.totalTime + 's后重新发送'
                    if (this.totalTime < 0) {
                        window.clearInterval(clock)
                        this.button = '重新发送验证码'
                        this.totalTime = 60
                        this.btnDisabled = false
                    }
                }, 1000)
            },

            //获取验证码
            getPhoneCode() {
                var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                if (this.ruleForm.regTelphone < 11 || !myreg.test(this.ruleForm.regTelphone.toString())) {
                    layer.msg('请检查或重新输入手机号')
                    return
                };
                this.$post("/api/v1/sms/code", {
                    'mobile': this.ruleForm.regTelphone,
                    'type': 4,
                }).then(res => {
                    if (res.code != 200) {
                        console.log(res)
                        // this.$message(res.msg)
                        layer.msg(res.msg, {});
                    } else {
                        // this.$alert("验证码已发送，注意查收")
                        this.countdown()
                    }
                })
            },

            //注册
            subRegister() {
                if (!this.showHook) {
                    // this.$message('请阅读并同意协议')
                    layer.msg('请阅读并同意协议', {});
                } else {
                    this.$post("/join", {
                        "code": this.ruleForm.codeNumber,
                        "joinType": "0",
                        "nickname": this.ruleForm.regUsername,
                        "password": this.ruleForm.regPassword,
                        "username": this.ruleForm.regTelphone,
                    }).then(res => {
                        if (res.code != 200) {
                            // this.$message(res.msg)
                            layer.msg(res.msg, {});
                        } else {
                            // this.$alert('注册成功')
                            // let clock = setTimeout(() => {
                            //     this.changeShow(2)
                            // }, 3000)
                            this.$alert('注册成功')
                            this.$emit('goLogin',2)
                        }
                    })
                }
            },
        },
    }
</script>

<style lang="scss" scoped>
    .limitWidth {
        margin: 5% 9%;
        text-align: center;

        .cTitle {
            font-size: 25px;
            margin: 15px 15px;
        }

        .el-input__inner {
            height: 55px;
            padding-left: 55px;
        }

        .phonePic {
            background-image: url("../../static/images/register/电话.png");
            background-repeat: no-repeat;
            width: 43px;
            height: 100%;
            position: absolute;
            top: 3px;
        }

        .namePic {
            background-image: url("../../static/images/register/用户名.png");
            background-repeat: no-repeat;
            width: 43px;
            height: 100%;
            position: absolute;
            top: 3px;

        }

        .passPic {
            background-image: url("../../static/images/register/密码.png");
            background-repeat: no-repeat;
            width: 43px;
            height: 100%;
            position: absolute;
            top: 3px;
        }

        .regButton {
            background-image: url("../../static/images/register/矩形 3 拷贝 3.png");
            background-size: 100% 100%;
            background-repeat: no-repeat;
            width: 100%;
            color: #FFFFFF;
            font-size: 20px;
            letter-spacing: 5px;
        }

        .regBtnTop {
            margin-bottom: 3%;
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            margin-right: 5%;
            margin-left: 5%
        }

        .regBtnBottom {
            margin-bottom: 5%;
            display: flex;
            justify-content: space-between;
            align-items: baseline;
        }

    }

</style>